package com.weixin.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.weixin.exception.WeiXinPropertyNullPointException;
import com.weixin.po.AccessToken;

public class WeiXinDBFactory extends WeiXinDBBaseFactory {

	private static Logger logger = LogManager.getLogger();
	private static Connection conn = null;
	private static PreparedStatement ps = null;
	private static ResultSet rs = null;

	private static String ACCESS_TOKEN_TABLE = "Token";
	private static String TICKET_TABLE = "ticket";

	/**
	 * 获取微信普通token
	 * 
	 * @return
	 * 
	 * @throws WeiXinPropertyNullPointException
	 * @throws SQLException
	 */
	public static AccessToken getAccessToken() throws WeiXinPropertyNullPointException, SQLException {
		conn = getConnection();
		String sql = "select * from " + ACCESS_TOKEN_TABLE + " order by id desc";
		AccessToken accessToken = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			accessToken = null;
			if (rs.next()) {
				accessToken = new AccessToken();
				accessToken.setId(rs.getInt("id"));
				accessToken.setToken(rs.getString("token"));
				accessToken.setTime(rs.getTimestamp("time").getTime());

				logger.debug(accessToken);
			}

			close(conn, ps, rs);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("get Accessoken failed ! sql : " + sql);
			logger.error("catch exception : " + WeixinCommonUtil.getStackTrace(e));
			throw e;
		}

		return accessToken;
	}

	/**
	 * save(in LJ platform , we use GZ database to store every token , so we
	 * needn't update . )
	 * 
	 * @deprecated
	 * @param accessToken
	 * @return
	 * @throws WeiXinPropertyNullPointException
	 * @throws SQLException
	 */
	public static boolean saveAccessToken(AccessToken accessToken)
			throws WeiXinPropertyNullPointException, SQLException {

		boolean flag = false;
		String sql = "update " + ACCESS_TOKEN_TABLE + " set token=? , expiresIn=? , lastTime=? ";
		conn = getConnection();
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, accessToken.getToken());
			// ps.setInt(2, accessToken.getExpiresIn());
			ps.setLong(3, accessToken.getTime());
			ps.executeUpdate();

			close(conn, ps);
			flag = true;
		} catch (SQLException e) {
			e.printStackTrace();

			flag = false;
			throw e;
		}

		return flag;
	}

	public static boolean insertAccessToken(AccessToken accessToken)
			throws WeiXinPropertyNullPointException, SQLException {

		logger.debug("insert : \n" + accessToken);

		boolean flag = false;
		String sql = "insert into " + ACCESS_TOKEN_TABLE + "(token,time) values(?,?)";
		conn = getConnection();
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, accessToken.getToken());
			ps.setTimestamp(2, new Timestamp(accessToken.getTime()));
			ps.executeUpdate();

			close(conn, ps);
			flag = true;
		} catch (SQLException e) {
			e.printStackTrace();
			flag = false;
			throw e;
		}

		return flag;
	}

	public static Map<String, Object> getWeiXinJsApiTicket() throws SQLException {
		conn = getConnection();
		String sql = "select * from " + TICKET_TABLE;
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if (rs.next()) {
				map.put("ticket", rs.getString("ticket"));
				map.put("timestamp", rs.getTimestamp("timestamp"));
			}

			close(conn, ps, rs);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("get Accessoken failed !");
			logger.error("catch exception : " + WeixinCommonUtil.getStackTrace(e));
			throw e;
		}

		return map;

	}

	public static boolean insertWeiXinJsApiTicket(String ticket, String timestamp)
			throws WeiXinPropertyNullPointException, SQLException {
		String sql = "insert into " + TICKET_TABLE + " values(?,?)";
		conn = getConnection();
		boolean flag = false;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, ticket);
			ps.setTimestamp(2, new Timestamp(Long.parseLong(timestamp)));

			ps.executeUpdate();
			close(conn, ps);
			flag = true;
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("failed to insert into jsapiticket !");
			logger.error("catch exception : " + WeixinCommonUtil.getStackTrace(e));
			throw e;
		}

		return flag;
	}

	public static boolean updateWeiXinJsApiTicket(String ticket, String timestamp)
			throws WeiXinPropertyNullPointException, SQLException {
		String sql = "update " + TICKET_TABLE + " set ticket = ? ,  timestamp = ? ";
		conn = getConnection();
		boolean flag = false;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, ticket);
			ps.setTimestamp(2, new Timestamp(Long.parseLong(timestamp)));
			ps.executeUpdate();

			flag = true;
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("failed to update jsapiticket !");
			logger.error("catch exception : " + WeixinCommonUtil.getStackTrace(e));
			throw e;
		}

		return flag;
	}
}
